package com.htt.base_library.network

import com.htt.base_library.constant.BaseConstant
import com.htt.base_library.util.LogUtils
import com.tencent.mmkv.MMKV
import com.test.library_base.BuildConfig
import okhttp3.HttpUrl
import okhttp3.HttpUrl.Companion.toHttpUrlOrNull
import okhttp3.Interceptor
import okhttp3.Response


/**
 * @ClassName DomainSwitchInterceptor
 * @Description TODO
 * @Author Hong
 * @Date 2022/9/1 16:52
 * @Version 1.0
 */
class DomainSwitchInterceptor : Interceptor {
    override fun intercept(chain: Interceptor.Chain): Response {
        //获取request
        val request = chain.request()
        val domain = "https://${MMKV.defaultMMKV().decodeString("BASE_URL_DOMAIN")}"
        return if (domain != BaseConstant.BASE_URL) {
            //获取request的创建者builder
            val builder = request.newBuilder()
            //从request中获取原有的HttpUrl实例oldHttpUrl
            val oldHttpUrl = request.url
            val newBaseUrl = domain.toHttpUrlOrNull()
            //重建新的HttpUrl，修改需要修改的url部分
            val newFullUrl = oldHttpUrl
                .newBuilder()
                .scheme(newBaseUrl!!.scheme)
                .host(newBaseUrl!!.host)
                .port(newBaseUrl!!.port)
                .build()
            LogUtils.e("scheme:${newBaseUrl!!.scheme}")
            LogUtils.e("host:${newBaseUrl!!.host}")
            LogUtils.e("port:${newBaseUrl!!.port}")
            //重建这个request，通过builder.url(newFullUrl).build()；
            //然后返回一个response至此结束修改
            chain.proceed(builder.url(newFullUrl).build())
        } else {
            chain.proceed(request)
        }

    }
}